package com.jason.kotlin.banner

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.jason.kotlin.R
import com.jason.kotlin.api.ApiService
import com.jason.kotlin.core.RetrofitManager
import com.jason.kotlin.model.BannerEntity
import kotlinx.android.synthetic.main.activity_banner_list.*
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * Description:BannerListActivity
 *
 * @author chenbaoyang
 * @create 2020/12/24 14:33
 */
class BannerListActivity : AppCompatActivity() {

    var bannerList = arrayListOf<BannerEntity>()
    lateinit var adapter: BannerListAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_banner_list)

        adapter = BannerListAdapter(this)
        recycler.layoutManager = LinearLayoutManager(this)
        recycler.setHasFixedSize(true)
        recycler.adapter = adapter

        GlobalScope.launch(Dispatchers.Main) {
            loadBanners()
            text.text = "获得了${bannerList.size}条数据"
            adapter.setBanners(bannerList)
        }
    }

    private suspend fun loadBanners() {
        var data = withContext(Dispatchers.IO) {
            RetrofitManager.getService(ApiService::class.java).getBanners()
        }
        data.let {
            bannerList.addAll(data.data)
        }
    }
}